<template>
  <div class="monitor-system">
    <!-- 系统标题和用户信息 -->
    <div class="header">
      <div class="user-info">
        <span>班主任：{{ user.name }}
        </span>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧监控区域 -->
      <div class="monitor-section">
        <!-- 实时视频监控 -->
        <div class="video-container">
          <h2>{{ currentClassroom }} 实时监控</h2>
          <video
            ref="videoPlayer"
            controls
            autoplay
            muted
            class="live-video"
            @error="handleVideoError"
          >
            您的浏览器不支持视频播放
          </video>
          <div class="video-controls">
            <el-button-group>
              <!-- <el-button @click="switchCamera('front')" size="small">前摄像头</el-button>
              <el-button @click="switchCamera('back')" size="small">后摄像头</el-button> -->
              <el-button @click="toggleFullscreen" size="small">全屏</el-button>
            </el-button-group>
          </div>
        </div>

        <!-- 告警信息 -->
        <div class="alarm-section">
          <h2>实时告警</h2>
          <div v-if="alarms.length === 0" class="no-alarms">暂无告警信息</div>
          <el-scrollbar height="200px">
            <div
              v-for="alarm in alarms"
              :key="alarm.id"
              class="alarm-item"
              :class="`alarm-${alarm.level}`"
            >
              <div class="alarm-time">{{ formatTime(alarm.time) }}</div>
              <div class="alarm-content">
                <strong>{{ alarm.studentName }}</strong> - {{ alarm.message }}
              </div>
              <el-button
                size="small"
                @click="viewStudentDetail(alarm.studentId)"
                class="alarm-action"
              >
                查看详情
              </el-button>
            </div>
          </el-scrollbar>
        </div>
      </div>

      <!-- 右侧信息区 -->
      <div class="info-section">
        <el-tabs type="border-card" v-model="activeTab">
          <!-- 学生异常情况 -->
          <el-tab-pane label="学生异常情况" name="abnormal">
            <div class="filter-bar">
              <el-input
                v-model="studentFilter"
                placeholder="搜索学生姓名"
                clearable
                style="width: 200px"
                @change="filterStudents"
              />
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="filterStudents"
              />
              <el-button type="primary" @click="exportAbnormalData" style="margin-left: auto">
                导出数据
              </el-button>
            </div>

            <el-table :data="filteredAbnormalRecords" style="width: 100%" height="400">
              <el-table-column prop="studentName" label="姓名" width="100" />
              <el-table-column prop="studentId" label="学号" width="120" />
              <el-table-column prop="type" label="异常类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getAbnormalTypeTag(row.type)">
                    {{ row.type }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="time" label="时间" width="180" />
              <el-table-column prop="description" label="详细描述" />
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button size="small" @click="viewStudentDetail(row.studentId)">
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 学生心理评测报告 -->
          <el-tab-pane label="心理评测报告" name="psychological">
            <div class="student-selector">
              <el-select
                v-model="selectedStudent"
                placeholder="选择学生"
                filterable
                style="width: 300px"
              >
                <el-option
                  v-for="student in students"
                  :key="student.id"
                  :label="`${student.name} (${student.id})`"
                  :value="student.id"
                />
              </el-select>
              <el-button type="primary" @click="generateReport" :disabled="!selectedStudent">
                生成报告
              </el-button>
            </div>

            <div v-if="reportLoading" class="report-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>AI正在生成心理评测报告...</span>
            </div>

            <div v-if="currentReport" class="report-container">
              <div class="report-header">
                <h3>{{ currentReport.studentName }} 心理评测报告</h3>
                <div class="report-meta">
                  <span>生成时间：{{ currentReport.generateTime }}</span>
                  <el-button size="small" @click="downloadReport">下载报告</el-button>
                </div>
              </div>

              <el-divider />

              <div class="report-content">
                <div v-for="(section, index) in currentReport.sections" :key="index">
                  <h4>{{ section.title }}</h4>
                  <p>{{ section.content }}</p>
                  <div v-if="section.chart" class="report-chart">
                    <!-- 这里可以放置图表 -->
                    <el-progress
                      v-if="section.score"
                      :percentage="section.score"
                      :color="getScoreColor(section.score)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';

// 用户信息
const user = ref({
  id: 't001',
  name: '张老师',
  role: '班主任',
});

// 当前教室
const currentClassroom = ref('高三(1)班');

// 视频流
const videoPlayer = ref(null);
const streamUrl = ref('');
const currentCamera = ref('front');

// 告警信息
const alarms = ref([
  {
    id: 'a001',
    level: 'high',
    studentId: 's001',
    studentName: '张三',
    message: '检测到异常行为：频繁离开座位',
    time: new Date(),
  },
  {
    id: 'a002',
    level: 'medium',
    studentId: 's005',
    studentName: '李四',
    message: '检测到上课睡觉行为',
    time: new Date(Date.now() - 1000 * 60 * 5),
  },
]);

// 学生异常记录
const abnormalRecords = ref([
  {
    id: 'r001',
    studentId: 's001',
    studentName: '张三',
    type: '行为异常',
    time: '2023-11-15 10:23:45',
    description: '上课期间频繁离开座位，共检测到5次',
  },
  // 更多记录...
]);

// 学生列表
const students = ref([
  { id: 's001', name: '张三', class: '高三(1)班' },
  { id: 's002', name: '李四', class: '高三(1)班' },
  // 更多学生...
]);

// 心理评测报告
const selectedStudent = ref('');
const reportLoading = ref(false);
const currentReport = ref(null);

// 筛选条件
const activeTab = ref('abnormal');
const studentFilter = ref('');
const dateRange = ref([]);
const filteredAbnormalRecords = ref([...abnormalRecords.value]);
const timer = ref({})

// 初始化视频流
onMounted(() => {
  initVideoStream();
  // 模拟实时告警
  simulateAlarms();
});
onUnmounted(() => {
  //清除定时器
  clearInterval(timer.value);
})

// 初始化视频流
function initVideoStream() {
  // 实际项目中替换为真实视频流URL
  streamUrl.value =
    currentCamera.value === 'front'
      ? 'https://example.com/stream/front'
      : 'https://example.com/stream/back';

  if (videoPlayer.value) {
    videoPlayer.value.src = streamUrl.value;
    videoPlayer.value.load();
  }
}

// 切换摄像头
function switchCamera(camera) {
  currentCamera.value = camera;
  initVideoStream();
}

// 全屏切换
function toggleFullscreen() {
  if (!document.fullscreenElement) {
    videoPlayer.value.requestFullscreen().catch((err) => {
      ElMessage.error(`全屏模式错误: ${err.message}`);
    });
  } else {
    document.exitFullscreen();
  }
}

// 视频错误处理
function handleVideoError() {
  ElMessage.error('视频流加载失败，请检查网络连接');
}

// 格式化时间
function formatTime(date) {
  return date.toLocaleTimeString();
}

// 查看学生详情
function viewStudentDetail(studentId) {
  // 实际项目中可以打开详情对话框或跳转页面
  ElMessage.info(`查看学生详情: ${studentId}`);
  activeTab.value = 'psychological';
  selectedStudent.value = studentId;
}

// 筛选学生异常记录
function filterStudents() {
  filteredAbnormalRecords.value = abnormalRecords.value.filter((record) => {
    const nameMatch = record.studentName.includes(studentFilter.value);
    let dateMatch = true;

    if (dateRange.value && dateRange.value.length === 2) {
      const recordDate = new Date(record.time);
      dateMatch = recordDate >= dateRange.value[0] && recordDate <= dateRange.value[1];
    }

    return nameMatch && dateMatch;
  });
}

// 导出异常数据
function exportAbnormalData() {
  // 实际项目中实现导出逻辑
  ElMessage.success('数据导出成功');
}

// 生成心理评测报告
async function generateReport() {
  reportLoading.value = true;

  // 模拟API请求延迟
   
    const student = students.value.find((s) => s.id === selectedStudent.value);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    currentReport.value = {
      studentId: student.id,
      studentName: student.name,
      generateTime: new Date().toLocaleString(),
      sections: [
        {
          title: '情绪状态评估',
          content:
            '根据AI分析，该学生近期情绪较为稳定，但存在轻度焦虑表现。建议关注其课间活动情况。',
          score: 72,
        },
        {
          title: '学习专注度分析',
          content: '课堂专注度评分中等，存在注意力分散情况，特别是在下午课程中表现明显。',
          score: 65,
        },
        {
          title: '社交互动评估',
          content: '社交活跃度良好，与同学互动频繁，未发现明显社交障碍。',
          score: 85,
        },
        {
          title: '综合建议',
          content:
            '建议：1. 适当安排课间放松活动；2. 关注下午课程的学习状态；3. 鼓励参与集体活动。',
        },
      ],
    };

    reportLoading.value = false;
   
}

// 下载报告
function downloadReport() {
  ElMessage.success('报告下载成功');
}

// 获取异常类型标签样式
function getAbnormalTypeTag(type) {
  const map = {
    行为异常: 'warning',
    考勤异常: 'danger',
    学习异常: 'info',
  };
  return map[type] || '';
}

// 获取分数颜色
function getScoreColor(score) {
  if (score >= 80) return '#67C23A';
  if (score >= 60) return '#E6A23C';
  return '#F56C6C';
}

// 模拟实时告警
function simulateAlarms() {
  timer.value = setInterval(() => {
    if (Math.random() > 0.7) {
      const randomStudent = students.value[Math.floor(Math.random() * students.value.length)];
      const newAlarm = {
        id: `a${Date.now()}`,
        level: ['low', 'medium', 'high'][Math.floor(Math.random() * 3)],
        studentId: randomStudent.id,
        studentName: randomStudent.name,
        message: ['检测到上课睡觉行为', '检测到频繁离座', '检测到使用手机', '检测到与他人频繁交谈'][
          Math.floor(Math.random() * 4)
        ],
        time: new Date(),
      };
      alarms.value.unshift(newAlarm);

      // 显示通知
      ElMessage.warning(`新告警: ${randomStudent.name} - ${newAlarm.message}`);       

    }
    
  }, 3000);
}
</script>

<style lang="scss" scoped>
@use './my-class-manage.scss';
</style>
